// 产生单个"水管"
class Pipe extends Rectangle {
  constructor(height, top, speed, pipeDom) {
    super(52, height, gameDom.clientWidth, top, speed, 0, pipeDom);
    console.log("gameDom.clientWidth", gameDom.clientWidth);
  }
  onMove() {
    // 当水管移动到内容区域外时，移除该dom对象
    if (this.left < -this.width) {
      this.dom.remove();
    }
  }
}

const getRandom = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min);
};

// 产生一对 "水管"
class PipePair {
  constructor(speed) {
    // 管道的上下间隙
    this.spaceHeight = 150;
    // 管道的最大与最小高度
    this.minHeight = 50;
    this.maxHeight = skyHeight - this.spaceHeight - this.minHeight;
    // 计算上/下管道的高度
    const upHeight = getRandom(this.minHeight, this.maxHeight);
    const downHeight = skyHeight - upHeight - this.spaceHeight;
    const downTop = skyHeight - downHeight;

    const upDom = document.createElement("div");
    upDom.className = "pipe up";

    const downDom = document.createElement("div");
    downDom.className = "pipe down";

    this.upPipe = new Pipe(upHeight, 0, speed, upDom);
    this.downPipe = new Pipe(downHeight, downTop, speed, downDom);

    gameDom.appendChild(upDom);
    gameDom.appendChild(downDom);
  }
  move(duration) {
    this.upPipe.move(duration);
    this.downPipe.move(duration);
  }
}

// 多个水管对
class PipePairProducer {
  constructor(speed) {
    this.pipePairs = [];
    this.tick = 1500;
    this.timer = null;
    this.speed = speed;
  }

  // 判断水管对是否已经超出内容区域
  get useLessPipePair() {
    return this.upPipe.left < -this.upPipe.width;
  }

  // 开始产生水管对
  startProducer() {
    if (this.timer) {
      return;
    }
    this.timer = setInterval(() => {
      const pipePair = new PipePair(this.speed);
      this.pipePairs.push(pipePair);
      // 移除掉不用的(超出内容区域) "水管"对
      for (let i = 0; i < this.pipePairs.length; i++) {
        const item = this.pipePairs[i];
        if (item.useLessPipePair) {
          this.pipePairs.splice(i, 1);
          i--;
        }
      }
    }, this.tick);
  }

  // 停止产生水管对
  stopProducer() {
    clearInterval(this.timer);
    this.timer = null;
  }
}
